package com.compass.controller.tool;

import com.alibaba.fastjson.JSON;
import com.compass.vo.Http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: li
 * Date: 2019/3/16
 * Time: 18:40
 * PROJECT：compass
 * PACKAGE: com.compass
 *
 * @author:55324936@qq.com To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/http")
public class HttpController {
    @RequestMapping("/httpPage")
    public ModelAndView httpPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/tool/http");
        return modelAndView;
    }

    @RequestMapping("/invoke")
    public @ResponseBody
    String invoke(Http http){
        HttpClient httpClient= HttpClients.createDefault();
        try {
            String interfaceName=http.getInterfaceName();
            URIBuilder uriBuilder = new URIBuilder(http.getInterfaceName());
            String interfaceMethod=http.getInterfaceMethod();
            String param =http.getParam();
            Map<String,String> paramMap= JSON.parseObject(param,Map.class);
            if(!CollectionUtils.isEmpty(paramMap)) {
                paramMap.forEach((k, v) -> {
                    uriBuilder.addParameter(k, v);
                });
            }
            HttpRequestBase httpRequestBase = null;
            if(interfaceMethod.equalsIgnoreCase("GET")){
                httpRequestBase = new HttpGet(uriBuilder.build());
            }else {
                httpRequestBase =new HttpPost(uriBuilder.build());
            }
            String body =http.getBody();
            if(!StringUtils.isEmpty(body)) {
                StringEntity stringEntity = new StringEntity(body,http.getEncoding());
                ((HttpPost)httpRequestBase).setEntity(stringEntity);
            }
            String headers =http.getHeaders();
            Map<String,String> headerMap=JSON.parseObject(headers,Map.class);
            if(!CollectionUtils.isEmpty(headerMap)) {
                HttpRequestBase finalHttpRequestBase = httpRequestBase;
                headerMap.forEach((k, v) -> {
                    finalHttpRequestBase.addHeader(k, v);
                });
            }
            httpRequestBase.setHeader("charset",http.getEncoding());
            RequestConfig.Builder requestConfig=RequestConfig.custom();
            requestConfig.setSocketTimeout(http.getTimeout()*1000);

            httpRequestBase.setConfig(requestConfig.build());
            HttpResponse httpResponse = httpClient.execute(httpRequestBase);
            HttpEntity httpEntity = httpResponse.getEntity();
            int code = httpResponse.getStatusLine().getStatusCode();
            System.err.println(code);
            String result = EntityUtils.toString(httpEntity);
            System.err.println(result);
            return result;
        }catch (java.net.UnknownHostException u) {
            return  "无法解析该域名,请确认请求地址是否正确!";
        }
        catch (MalformedURLException m){
            return  "请在URL加上Http://";
        } catch (SocketTimeoutException t){
            return "请求超时";
        }
        catch (URISyntaxException e) {
            e.printStackTrace();
            return "url错误,请检查url是否包含特殊字符";
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
